#!/usr/bin/perl
# Author: Lipyeow Lim
# Date  : 12/21/2010

use Data::Dumper;
use GraphViz;


use strict;

scalar @ARGV==1 or 
   die "Usage: plan2dot.pl <plan file>\n";

my $planfile=$ARGV[0];
open( PLAN, "<$planfile") or 
   die "Cannot open plan file $planfile!\n"; 
my @lines = <PLAN>;
close PLAN;

my $plan;

eval join(" ",@lines);

plan2dot($plan)->as_png("$planfile.png");

#------------------------------------------------
#------------------------------------------------
sub plan2dot
{
   my ($qep) = @_;


   my $g = GraphViz->new(directed=>1, layout=>'dot',
           rankdir=>'1');
   my %outhosts = ();
   my %ophosts= ();
   my %inport2nid=();

   $g->add_node('n0', label=>"Union ResultSet");
   # first pass, add all the nodes
   my $nid=1;
   foreach my $op (@$qep)
   {
      my $curhost = $op->[0];
      my $opName = $op->[1]->{'cmd'};
      my ($dbfile,$sql,$arg) =
         split(/:/,$op->[1]->{'args'});

      $sql =~ s/FROM/\\nFROM/;
      $sql =~ s/WHERE/\\nWHERE/;
      $g->add_node("n$nid", label=> "$opName\n$sql");

      foreach my $inport (@{$op->[1]->{'input'}})
      {
         $inport2nid{$inport}=$nid;
      } 
      $nid++;
   }
   my $nid=1;
   foreach my $op (@$qep)
   {
      foreach my $outport (@{$op->[1]->{'output'}})
      {
         if( ! exists $inport2nid{$outport})
         {
            $g->add_edge("n$nid" => 'n0');
         }
         else
         {
            $g->add_edge("n$nid" => $inport2nid{$outport});
         }
      } 
      $nid++;
   }
   return $g;
}


